//
//  HeartRateReminderViewController.m
//  StormWatch
//
//  Created by 王岩 on 2024/9/5.
//

#import "HeartRateReminderViewController.h"
#import <BRPickerView/BRDatePickerView.h>
@interface HeartRateReminderViewController ()

@property (weak, nonatomic) IBOutlet UILabel *switchLab;
@property (weak, nonatomic) IBOutlet UILabel *startTimeLab;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLab;
@property (weak, nonatomic) IBOutlet UILabel *durationTimeLab;

@property (weak, nonatomic) IBOutlet UISwitch *switchBtn;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *endBtn;
@property (weak, nonatomic) IBOutlet UIButton *durationBtn;

/* <#note#> */
@property (nonatomic, assign) unsigned long switchValue, start_H, start_M, end_H, end_M, durationValue;

@end

@implementation HeartRateReminderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.switchLab.text = SWString(@"On/Off");
    self.startTimeLab.text = SWString(@"Timer");
    self.endTimeLab.text = SWString(@"End Time");
    self.durationTimeLab.text = SWString(@"Duration time");
    
    self.startBtn.contentHorizontalAlignment = self.endBtn.contentHorizontalAlignment = self.durationBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    
    if (self.type == Command_HeartRateReminders) {
        self.navigationItem.title = SWString(@"Scheduled heart rate reminders");
    }else if (self.type == Command_Sedentary) {
        self.navigationItem.title = SWString(@"Sedentary reminder");
    }else if (self.type == Command_RaiseHand) {
        self.navigationItem.title = SWString(@"Raise hand to brighten screen");
        self.durationBtn.hidden = self.durationTimeLab.hidden = YES;
    }
    
    
    [SWInitializer jy_initRedButtonWithTarget:self action:@selector(clickSureBtnAction) frame:CGRectMake(0, 0, kScreenWidth - 100, 50) title:SWString(@"Confirm") on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(50);
        kMakeBV(-100);
        kMakeWHV(kScreenWidth-100, 50);
    }];
    
  
    [self readData];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)updateUI {
    if (self.switchBtn.on) {
        self.startBtn.hidden = self.startTimeLab.hidden = self.endBtn.hidden = self.endTimeLab.hidden = NO;
        if (self.type != Command_RaiseHand) {
            self.durationBtn.hidden = self.durationTimeLab.hidden = NO;
        }
        NSString * start = [NSString stringWithFormat:@"%02lu:%02lu",self.start_H, self.start_M];
        NSString * end = [NSString stringWithFormat:@"%02lu:%02lu",self.end_H, self.end_M];
        NSString * duration = [NSString stringWithFormat:@"%lu%@",self.durationValue, SWString(@"minute")];
        
        [self.startBtn setTitle:start forState:0];
        [self.endBtn setTitle:end forState:0];
        [self.durationBtn setTitle:duration forState:0];
        
    }else {
        self.startBtn.hidden = self.startTimeLab.hidden = self.endBtn.hidden = self.endTimeLab.hidden = self.durationBtn.hidden = self.durationTimeLab.hidden = YES;
    }
}

- (IBAction)clickSwithBtn:(UISwitch *)sender {
    [self updateUI];
}

- (void)readData {
    if (self.type == Command_HeartRateReminders || self.type == Command_Sedentary) {
        [[StormCommandTool sharedInstance] readStormCommand:self.type reBack:^(NSString * _Nonnull backData) {
            if (backData) {
                NSString * valueStr = [backData substringWithRange:NSMakeRange(26, 2)];
                unsigned long value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                self.switchValue = value;
                NSLog(@"开关数值：%lu",value);
                // 开关状态（0：关闭，1：打开）
                if (value == 1) {
                    valueStr = [backData substringWithRange:NSMakeRange(28, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"开始时间_时：%lu",value);
                    self.start_H = value;
                    
                    valueStr = [backData substringWithRange:NSMakeRange(30, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"开始时间—分：%lu",value);
                    self.start_M = value;
                    
                    valueStr = [backData substringWithRange:NSMakeRange(32, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"结束时间—时：%lu",value);
                    self.end_H = value;
                    
                    valueStr = [backData substringWithRange:NSMakeRange(34, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"结束时间—分：%lu",value);
                    self.end_M = value;
                    
                    valueStr = [backData substringWithRange:NSMakeRange(36, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"间隔时间：%lu",value);
                    self.durationValue = value;
                    
                }else {
                    self.switchBtn.on = NO;
                    [self clickSwithBtn:self.switchBtn];
                }
                
                [self updateUI];
                
            }
        }];
    }else if (self.type == Command_RaiseHand) {
        [[StormCommandTool sharedInstance] readStormCommand:self.type reBack:^(NSString * _Nonnull backData) {
            if (backData) {
                NSString * valueStr = [backData substringWithRange:NSMakeRange(26, 2)];
                unsigned long value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                self.switchValue = value;
                NSLog(@"开关数值：%lu",value);
                // 开关状态（0：关闭，1：打开）
                if (value == 1) {
                    valueStr = [backData substringWithRange:NSMakeRange(28, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"开始时间_时：%lu",value);
                    self.start_H = value;
                    
                    valueStr = [backData substringWithRange:NSMakeRange(30, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"开始时间—分：%lu",value);
                    self.start_M = value;
                    
                    valueStr = [backData substringWithRange:NSMakeRange(32, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"结束时间—时：%lu",value);
                    self.end_H = value;
                    
                    valueStr = [backData substringWithRange:NSMakeRange(34, 2)];
                    value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
                    NSLog(@"结束时间—分：%lu",value);
                    self.end_M = value;
                    
                }else {
                    self.switchBtn.on = NO;
                    [self clickSwithBtn:self.switchBtn];
                }
                
                [self updateUI];
                
            }
        }];
    }
}

- (void) clickSureBtnAction {
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    unsigned char byte0 = (self.switchBtn.isOn & 0xff);
    arr[0] = @(byte0);
    unsigned char byte1 = (self.start_H & 0xff);
    arr[1] = @(byte1);
    unsigned char byte2 = (self.start_M & 0xff);
    arr[2] = @(byte2);
    unsigned char byte3 = (self.end_H & 0xff);
    arr[3] = @(byte3);
    unsigned char byte4 = (self.end_M & 0xff);
    arr[4] = @(byte4);
    if (self.type != Command_RaiseHand) {
        unsigned char byte5 = (self.durationValue & 0xff);
        arr[5] = @(byte5);
    }
   
    [[StormCommandTool sharedInstance] writeStormCommand:self.type Value:arr reBack:^(NSString * _Nonnull backData) {
        if (backData) {
            if ([backData hasSuffix:@"00"]) {
                toast(SWString(@"Success"));
            }else {
                toast(SWString(@""));
            }
//            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}
- (IBAction)clickStartTImeBtn:(UIButton *)sender {
    [BRDatePickerView showDatePickerWithMode:BRDatePickerModeHM title:nil selectValue:nil resultBlock:^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
        NSArray * arr = [selectValue componentsSeparatedByString:@":"];
        self.start_H = [arr.firstObject longLongValue];
        self.start_M = [arr.lastObject longLongValue];
        [self updateUI];
    }];
}
- (IBAction)clickEndTImeBtn:(UIButton *)sender {
    [BRDatePickerView showDatePickerWithMode:BRDatePickerModeHM title:nil selectValue:nil resultBlock:^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
        NSArray * arr = [selectValue componentsSeparatedByString:@":"];
        self.end_H = [arr.firstObject longLongValue];
        self.end_M = [arr.lastObject longLongValue];
        [self updateUI];
    }];
}
- (IBAction)clickDurationTImeBtn:(UIButton *)sender {
  
    
    __block UITextField *tf = nil;
    [LEEAlert alert].config
    .LeeTitle(SWString(@"Duration time"))
    .LeeContent(SWString(@"Time-lapse minute must be within 1-255 minutes"))
    .LeeAddTextField(^(UITextField *textField) {
        // 这里可以进行自定义的设置
        textField.placeholder = SWString(@"Enter time-lapse (minute)");
        if (@available(iOS 13.0, *)) {
            textField.textColor = [UIColor secondaryLabelColor];
        } else {
            textField.textColor = [UIColor darkGrayColor];
        }
        textField.keyboardType = UIKeyboardTypeNumberPad;
        tf = textField; //赋值
    })
    .LeeAction(SWString(@"Confirm"), ^{
        self.durationValue = tf.text.longLongValue;
        [self updateUI];
    })
    .leeShouldActionClickClose(^(NSInteger index){
        // 是否可以关闭回调, 当即将关闭时会被调用 根据返回值决定是否执行关闭处理
        // 这里演示了与输入框非空校验结合的例子
        BOOL result = ![tf.text isEqualToString:@""];
        result = index == 0 ? result : YES;
        return result;
    })
    .LeeCancelAction(SWString(@"Cancel"), nil) // 点击事件的Block如果不需要可以传nil
    .LeeShow();
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
